// import styles from "./index.module.less";
import { Space, Table, Button, Form, Input, Modal, message} from "antd";
import type { TableColumnsType } from "antd";
import api from "../../api/index.ts";
import { useEffect, useRef, useState } from "react";
import type { IDept } from "../../types/api.ts";
import { formatISODateToLocal } from "../../until/index.ts";
import CreateDept from "./CreateDept.tsx";

const Dept = () => {

  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    getDeptData();
  }, []);
  
  // 这里的ts useRef 本身是类型无关的，但通过泛型可以明确指定 ref.current 应该存储什么类型的数据。
  // 也就是说useRef 后面的泛型，定义的是ref.current的类型
  // 这里showModal传入了一个data，可有可无，他有个两个类型可选(联合类型)，一个类型是IDept，另一个是将data进行结构，拿出里面的parentId字段，是string类型。
  const deptModelRef = useRef<{showModal: (type:string, data?:IDept | { parentId: string }) => void;}>(null) 

  const [deptData, setDeptData] = useState<IDept[]>([]);

  const getDeptData = async () => {
    const res = await api.getDepartmentList(form.getFieldsValue());
    setDeptData(res);
  };

  const [form] = Form.useForm();

  // table的列配置信息
  const columns: TableColumnsType<IDept> = [
    {
      title: "部门名称",
      dataIndex: "deptName",
      key: "deptName",
      width: "200",
    },
    {
      title: "负责人",
      dataIndex: "userName",
      key: "userName",
      width: "150",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text) => {
        return text ? formatISODateToLocal(text) : '';
      },
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
      render: (text) => {
        return text ? formatISODateToLocal(text) : '';
      },
    },
    {
      title: "操作",
      key: "action",
      width: "200",
      render: (_, record) => {
        // render 第一个参数是当前列对应行的键的值,如果是当前没有(就是单纯只存放了按钮那就返回的是整行row的数据)
        // 第二个参数恒定返回整行的数据
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                handleSubCreate(record._id!);
              }}
            >
              新增
            </Button>
            <Button
              type="primary"
              onClick={() => {
                handleSubEdite(record);
              }}
            >
              编辑
            </Button>
            
            <Button danger onClick={()=> {handleSubDel(record._id)}}>
              删除
            </Button>
          
          </Space>
        );
      },
    },
  ];
  
 const data: IDept[] = [
      {
        _id: "saidgasgdaysgda22aa3",
        createTime: "2023-11-22T08:23:39.919Z",
        updateTime: "2023-11-22T08:23:39.919Z",
        deptName: "开发部",
        userName: "张三",
        children: [
          {
            _id: "saidgasgdaysgda23",
            createTime: "2023-11-22T08:23:39.919Z",
            updateTime: "2025-11-22T08:23:39.919Z",
            deptName: "前端开发部",
            userName: "李四",
            parentId: 1,
            children: [],
          },
        ],
      },
      {
        _id: "saidgasgdaysgdas223",
        createTime: "2021-11-22T08:23:39.919Z",
        updateTime: "2023-11-22T08:23:39.919Z",
        deptName: "业务部",
        userName: "张三",
        children: [
          {
            _id: "saidgasgdaysgda22s3",
            createTime: "2023-11-22T08:23:39.919Z",
            updateTime: "2023-11-22T08:23:39.919Z",
            deptName: "大宗贸易部",
            userName: "李四",
            parentId: 1,
            children: [],
          },
        ],
      },
    ];
  
  const handleSubCreate = (id: string) => {
    deptModelRef.current?.showModal('新建部门',{parentId: id})
  };
  const handleSubEdite = (record:IDept) => {
    console.log(record)
    deptModelRef.current?.showModal('编辑部门',record)
  };
  const handleSubDel = (id?: string) => {
    Modal.confirm({
      title: '确定删除该部门吗?',
      content: '一旦删除将不可恢复，请谨慎操作。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await api.deleteDept({deptId:id!});
        if(!res) {
          message.success('操作成功！'); 
        }
      },
      onCancel() {},
    });
  };

  const handleRest = () => {
    form.resetFields();
  };

  const handleCreate = () => {
     deptModelRef.current?.showModal("新建部门")
  };

  return (
    <>
      <Form className="search-form" layout="inline" form={form}>
        <Form.Item
          label="部门名称"
          name="deptName"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input placeholder="请输入部门名称" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="mr10">
            查询
          </Button>
          <Button type="primary" htmlType="button" onClick={handleRest}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className="warpTable">
        <div className="header">
          <div className="title">部门列表</div>
          <div className="action">
            <Button type="primary" htmlType="button" onClick={handleCreate}>
              新增
            </Button>
          </div>
        </div>
        <Table rowKey="_id" columns={columns} dataSource={data} />
      </div>
      <CreateDept updataList={getDeptData} ref={ deptModelRef }/>
    </>
  );
};
export default Dept;
